<template>
  <div class="app-container">
    <ContentWrap>
      <CustomBox>
        <el-row :gutter="20">
          <!-- <el-col :span="4">
            <RegionTree node-type="1" :node-click="handleDfqNodeClick"/>
          </el-col> -->

          <el-col :span="24" class="content-container">
            <el-tabs v-model="activeTab" @tab-click="handleTabClick">
              <el-tab-pane label="实时数据" name="realtime"></el-tab-pane>
              <el-tab-pane label="历史数据" name="history"></el-tab-pane>
            </el-tabs>

            <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch"
                     label-width="68px">

              <el-form-item label="报警状态" prop="warnStatus">
                <el-select v-model="queryParams.warnStatus" placeholder="请选择报警状态" clearable size="small">
                  <el-option
                    v-for="dict in dict.type.warn_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="报警类型" prop="warnType">
                <el-select v-model="queryParams.warnType" placeholder="请选择报警类型" clearable size="small">
                  <el-option
                    v-for="dict in dict.type.warn_type"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="处理状态" prop="handleStatus">
                <el-select v-model="queryParams.handleStatus" placeholder="请选择处理状态" clearable size="small">
                  <el-option
                    v-for="dict in dict.type.warn_handle_status"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="时间范围" prop="timeRange">
                <el-date-picker
                  v-model="dateRange"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始日期"
                  end-placeholder="结束日期"
                  value-format="yyyy-MM-dd"
                  @change="handleDateRangeChange"
                ></el-date-picker>
              </el-form-item>

              <el-form-item>
                <!-- <el-button type="warning" plain icon="el-icon-download" size="mini" @click="handleExport">导出
                </el-button> -->
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
              </el-form-item>
            </el-form>

            <el-table v-loading="loading" :data="warnList" border :height="getAvailableHeight">
              <el-table-column label="对象类型" align="center" width="100">
                <template slot-scope="scope">
                    <dict-tag :options="dict.type.warn_target_type" :value="scope.row.targetType"/>
                  </template>
              </el-table-column>
              <el-table-column label="名称" align="center" prop="targetID" width="170"/>

              <el-table-column label="报警状态" align="center" width="100" sortable>
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.warn_status" :value="scope.row.warnStatus"/>
                </template>
              </el-table-column>

              <el-table-column label="处理状态" align="center" width="100" sortable>
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.warn_handle_status" :value="scope.row.handleStatus"/>
                </template>
              </el-table-column>

              <el-table-column label="报警参数" align="center" width="150" sortable>
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.warn_param_type" :value="scope.row.warnParamType"/>
                </template>
              </el-table-column>

              <el-table-column label="报警类型" align="center" width="100" sortable>
                <template slot-scope="scope">
                  <dict-tag :options="dict.type.warn_type" :value="scope.row.warnType"/>
                </template>
              </el-table-column>

              <el-table-column label="开始时间" align="center" prop="StartTime" width="170" sortable>
              </el-table-column>
              <el-table-column label="最近报警时间" align="center"
                               prop="RecentlyWartTime"
                               width="170" sortable/>
              <el-table-column label="报警值" align="center"
                               prop="warnValue" width="110"/>
              <el-table-column label="参考值" align="center" prop="referenceValue" width="110" sortable/>
              <el-table-column label="差值" align="center" prop="value" width="110" sortable/>
              <el-table-column label="确认人" align="center" prop="confirmedBy" width="100" sortable/>
              <el-table-column label="操作" align="center" width="150" sortable>
              <template slot-scope="scope">
                <div v-if="scope.row.warnStatus === 0 && activeTab === 'realtime'">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-edit"
                    @click="handleConfirm(scope.row)"
                    v-hasPermi="['params:strategyParams:edit']"
                  >确认
                  </el-button>
                  <el-button v-if="activeTab === 'realtime'"
                    size="mini"
                    type="text"
                    icon="el-icon-delete"
                    @click="handleCancel(scope.row)"
                    v-hasPermi="['params:strategyParams:edit']"
                  >误报
                  </el-button>
                </div>
                <div v-else-if="scope.row.warnStatus === 1 && scope.row.handleStatus != 1 && scope.row.handleStatus != 2 && activeTab === 'realtime'">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-plus"
                    @click="handleAdd(scope.row)"
                    v-hasPermi="['system:deployment:add']"
                  >发起工单
                  </el-button>
                </div>
                <div v-else-if="scope.row.warnStatus === 1 && (scope.row.handleStatus === 1 || scope.row.handleStatus === 2) ">
                  <el-button
                    size="mini"
                    type="text"
                    icon="el-icon-tickets"
                    @click="handleFlowRecord(scope.row)"
                  >工单详情
                  </el-button>
                </div>
              </template>
            </el-table-column>
            </el-table>

            <pagination
              :total="total"
              :page-sizes="[15, 30, 45, 60]"
              :page.sync="queryParams.pageNum"
              :limit.sync="queryParams.pageSize"
              @pagination="getList"
            />
          </el-col>
        </el-row>
      </CustomBox>
    </ContentWrap>

    <!-- 发起流程 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form :model="queryProcessParams" ref="queryProcessForm" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="queryProcessParams.name"
            placeholder="请输入名称"
            clearable
            size="small"
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleProcessQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetProcessQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table v-loading="processLoading" fit :data="definitionList" border >
        <el-table-column label="流程名称" align="center" prop="name" />
        <el-table-column label="流程版本" align="center">
          <template slot-scope="scope">
            <el-tag size="medium" >v{{ scope.row.version }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="流程分类" align="center" prop="category" />
        <el-table-column label="操作" align="center" width="300" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-edit-outline"
              @click="handleStartProcess(scope.row)"
            >发起流程</el-button>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="processTotal>0"
        :total="processTotal"
        :page.sync="queryProcessParams.pageNum"
        :limit.sync="queryProcessParams.pageSize"
        @pagination="listDefinition"
      />
    </el-dialog>
  </div>
</template>

<script>
import {listWarnInfo,updateWarnInfo} from "@/api/leakage/warnInfo";
import {listWarnHistory,updateWarnHistory} from "@/api/leakage/warnHistory";
import RegionTree from "@/views/leakage/components/RegionTree.vue";
import {listDefinition,getProcessInfo,getProcessInfoHistory} from "@/api/flowable/definition";
import Cookies from "js-cookie";
import { cloneDeep } from 'lodash';

export default {
  name: "Warn_ss",
  dicts: ['warn_target_type', 'warn_param_type', 'warn_type', 'warn_status', 'warn_handle_status'],
  components: {RegionTree},
  data() {
    return {
      screenHeight: null,
      // 选项卡状态
      activeTab: 'realtime',
      // 遮罩层
      loading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 报警数据表格数据
      warnList: [],
      // 日期范围
      dateRange: [],
      // 历史数据日期范围
      historyDateRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 15,
        queryStartDate: null,
        queryEndDate: null,
        warnStatus: null,
        warnType: null,
        handleStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      definitionList:[],
      // 查询参数
      queryProcessParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        category: null,
        key: null,
        tenantId: null,
        deployTime: null,
        derivedFrom: null,
        derivedFromRoot: null,
        parentDeploymentId: null,
        engineVersion: null
      },
      // 总条数
      processTotal:0,
      // 我发起的流程列表数据
      myProcessList: [],
      // 遮罩层
      processLoading: true,
      warnId: null,
      procInsId: null,
      deployId: null,
      taskId: null,
    };
  },

  created() {
    this.getList();
    this.screenHeight = document.body.clientHeight
  },
  computed: {
    getAvailableHeight() {
      return this.screenHeight - 235
    },
  },
  methods: {
    /** 选项卡切换操作 */
    handleTabClick(tab) {
      this.queryParams = {
        pageNum: 1,
        pageSize: 15,
        queryStartDate: null,
        queryEndDate: null,
        warnStatus: null,
        warnType: null,
        handleStatus: null
      };
      this.getList();
    },
    /** 新增按钮操作 */
    handleAdd(row) {
      this.open = true;
      this.title = "发起工单";
      this.listDefinition();
      this.warnId = row.id;
      console.log(this.warnId);

    },
    listDefinition(){
      listDefinition(this.queryProcessParams).then(response => {
        this.definitionList = response.data.records;
        this.processTotal = response.data.total;
        this.processLoading = false;
      });
    },
    /**  发起流程申请 */
    handleStartProcess(row){
      this.$router.push({ path: '/flowable/task/myProcess/send/index',
        query: {
          deployId: row.deploymentId,
          procDefId: row.id,
          businessKey: this.warnId
          }
      })
    },

    handleFlowRecord(row){
      if(this.activeTab === 'realtime'){
        this.handleFlowRecordNow(row);
      } else {
        this.handleFlowRecordHistory(row);
      }
    },
    /** 流程流转记录 */
    async handleFlowRecordNow(row) {
      console.log("实时流程流转记录");
      try {
        const response = await getProcessInfo(row.id);
        const { processInstanceId, processDeploymentId, taskId } = response.data;
        console.log(response.data);

        this.$router.push({
          path: '/flowable/task/process/detail',
          query: { procInsId: processInstanceId, deployId: processDeploymentId, taskId }
        });
      } catch (error) {
        console.error('流程信息获取失败:', error);
        // 显示错误提示
      }
    },
    /** 历史流程流转记录 */
    async handleFlowRecordHistory(row) {
      console.log("历史流程流转记录");
      try {
        const response = await getProcessInfoHistory(row.id);
        const { processInstanceId, processDeploymentId, taskId } = response.data;
        console.log(response.data);

        this.$router.push({ path: '/flowable/task/finished/detail/index',
        query: {
          procInsId: processInstanceId,
          deployId: processDeploymentId,
          taskId: taskId,
        }})
      } catch (error) {
        console.error('流程信息获取失败:', error);
        // 显示错误提示
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.warnId = null;
      // this.reset();
    },
    /** 查询报警实时数据列表 */
    getList() {
      this.loading = true;
      if(this.activeTab === 'realtime') {
        listWarnInfo(this.queryParams).then(response => {
          this.warnList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      } else {
        listWarnHistory(this.queryParams).then(response => {
          this.warnList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      }
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.dateRange = [];
      this.historyDateRange = [];
      this.queryParams.queryStartDate = null;
      this.queryParams.queryEndDate = null;
      this.handleQuery();
    },
    /** 搜索按钮操作 */
    handleProcessQuery() {
      this.queryProcessParams.pageNum = 1;
      this.listDefinition();
    },
    /** 重置按钮操作 */
    resetProcessQuery() {
      this.resetForm("queryProcessForm");
      this.handleProcessQuery();
    },
    /** 确认操作 */
    handleConfirm(row) {
      // this.reset();
      const requestData = cloneDeep(row);
      requestData.confirmedBy = Cookies.get("username");
      console.log(Cookies.get("username"));

      requestData.warnStatus = 1
      console.log(requestData);

      this.$modal.confirm('是否确认报警？', '确认操作').then(() => {
        if(this.activeTab === 'realtime') {
        updateWarnInfo(requestData).then(response => {
          if(response.code == 200){
            this.$modal.msgSuccess("确认成功");
            this.getList();
          }
        });
      } else {
        updateWarnHistory(requestData).then(response => {
          if(response.code == 200){
            this.$modal.msgSuccess("确认成功");
            this.getList();
          }
        });
      }
      }).catch(() => {})
    },
    /** 误报操作 */
    handleCancel(row) {
      const requestData = cloneDeep(row);
      requestData.confirmedBy = Cookies.get("username");
      requestData.warnStatus = 2
      requestData.handleStatus = 1
      this.$modal.confirm('是否确认这是误报？', '确认操作').then(() => {
        if(this.activeTab === 'realtime') {
          updateWarnInfo(requestData).then(response => {
            if(response.code == 200){
              this.$modal.msgSuccess("修改成功");
              this.getList();
            }
          });
        }
      }).catch(() => {})
    },
    // /** 导出按钮操作 */
    // handleExport() {
    //   this.download('swla2/freezeDfq/export', {
    //     ...this.queryParams
    //   }, `大分区绩效报表.xlsx`)
    // },
    // handleDfqNodeClick(node) {
    //   const levelType = node.levelType
    //   if (levelType !== '1') {
    //     this.editingZone = undefined
    //     this.$message.error('请选择大分区节点')
    //   } else {
    //     this.editingZone = node
    //     this.handleQuery()
    //   }
    // },
    // getHbStyle(hb) {
    //   let color
    //   const fHb = parseFloat(hb)
    //   if (fHb > 0) {
    //     color = 'red'
    //   } else {
    //     color = 'green'
    //   }
    //   return {color: color}
    // },
    // getCxclStyle(cxcl) {
    //   let color
    //   const fCxcl = parseFloat(cxcl)
    //   if (fCxcl <= 0 || fCxcl > 30) {
    //     color = 'red'
    //   } else if (fCxcl > 0 && fCxcl < 10) {
    //     color = 'green'
    //   } else if (fCxcl > 10 && fCxcl < 20) {
    //     color = '#ffd400'
    //   } else if (fCxcl > 20 && fCxcl < 30) {
    //     color = '#ff9900'
    //   }

    //   return {color: color}
    // },

    /** 处理日期范围变化 */
    handleDateRangeChange(val) {
      if (val) {
        this.queryParams.queryStartDate = val[0];
        this.queryParams.queryEndDate = val[1];
      } else {
        this.queryParams.queryStartDate = null;
        this.queryParams.queryEndDate = null;
      }
    },
  }
};
</script>
